package com.my_service.administrator.texttool;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;


import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.my_service.administrator.texttool.zxing.android.CaptureActivity;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity  {
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    EditText deviceID, cameraID, roomID, bedID, bluetoothID;
    Button recBluetooth, recDevice,allButton,buttonCamera;
    private static final String DECODED_CONTENT_KEY = "deviceID";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";

    private static final String Bluetooth_CONTENT_KEY = "bluetoothID";
    private static final String Bluetooth_BITMAP_KEY = "codedBitmap";

    private static final int REQUEST_CODE_SCAN = 0x0000;
    List<String> list = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();
    String name;
    String address;
    BroadcastReceiver deviceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 从intent中获取设备
//                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 添加到列表

                name = bluetoothDevice.getName();
                address = bluetoothDevice.getAddress();
                list.add(name);
                list2.add(address);
                Log.e("test","name:"+name);
                Log.e("test","address:"+address);
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
//        if (bluetoothAdapter.isEnabled()) {
//            bluetoothAdapter.disable();
//        }
        openBluetooth();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙状态改变的广播
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//找到设备的广播
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索完成的广播
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始扫描的广播
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
        registerReceiver(deviceReceiver, intentFilter);
//        intentFilter.addAction(myService.ACTION_LOOBOT_FOUND);
    }

    private void init() {
        deviceID = findViewById(R.id.deviceID);
        cameraID = findViewById(R.id.cameraID);
        roomID = findViewById(R.id.roomID);
        bedID = findViewById(R.id.bedID);
        bluetoothID = findViewById(R.id.bluetoothID);
        recBluetooth = findViewById(R.id.receiveBluID);
        recDevice = findViewById(R.id.receiveDeviceID);
        allButton=findViewById(R.id.button);
        buttonCamera=findViewById(R.id.buttoncameraID);
        recDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceID.setText(getDeviceSN());
                Log.e("test", "getDeviceSN : " + getDeviceSN());
            }
        });
        buttonCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //动态权限申请
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    goScan();
                }
            }
        });
//        recBluetooth.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (name == null){
//                            Toast.makeText(MainActivity.this, "正在搜索蓝牙", Toast.LENGTH_SHORT).show();
//                        } else {
//                            bluIndex();
//                        }
//                    }
//                });
//
//            }
//        });
        allButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getOkHTTP();
            }
        });


    }
    /**
     * 跳转到扫码界面扫码
     */
    private void goScan(){
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    //也是设备号 不可靠
    private String getAndroidId() {
        String m_szAndroidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        Log.e("", "m_szAndroidID:" + m_szAndroidID);
        return m_szAndroidID;
    }

    //获取设备SN好
    public static String getDeviceSN() {
        String serialNumber = android.os.Build.SERIAL;
        return serialNumber;
    }

    public void openBluetooth() {
        if (bluetoothAdapter == null) {

        }
        //打开蓝牙
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
        }
    }

    int i;

    private void bluIndex() {
        final String[] adresss = list2.toArray(new String[list2.size()]);
        final String[] namee = list.toArray(new String[list.size()]);
        Log.e("test", "adress" + adresss[0] + "!!!!!!!!" + list2.size());
        Log.e("test", "name" + namee[0] + "!!!!!!!!!!!!!!" + list.size());
        i = 0;
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MainActivity.this);
        singleChoiceDialog.setTitle("请选则设备蓝牙");
        singleChoiceDialog.setSingleChoiceItems(namee, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                i = which;
                Log.e("test", "::::::::::::::::" + which);
                Log.e("test", "::::::::::::::::" + i);
            }
        });
        singleChoiceDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                if (i != -1) {
                Log.e("test", "name" + i);
                bluetoothID.setText(adresss[i]);
                Log.e("test", "adresss" + adresss[i]);
                Toast.makeText(MainActivity.this, "选择的是" + namee[i], Toast.LENGTH_SHORT).show();
                dialog.dismiss();
//                }
            }
        });
        singleChoiceDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                //返回的BitMap图像
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                cameraID.setText("" + content);
            }
        }
    }
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    private  void  getOkHTTP(){
        HashMap<String , String > map=new HashMap<>();
        map.put("bedNumberId","123");
        map.put("roomId","123");
        map.put("robotId","123");
        map.put("bluetoothMAC","123");
        map.put("cameraId","123");
        Gson gson=new Gson();
        String data=gson.toJson(map);
        RequestBody requestBody=RequestBody.create(JSON,data);
        Request request=new Request.Builder().url("http://23.239.96.3:8085/robot/addRobotMassage").post(requestBody).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }
            @Override
            public void onResponse(Response response) throws IOException {
                Log.e("test", "2、连接成功获取的内容" + response.body().string());
            }
        });
    }
//    private  void  setTest(){
//        int i;
//        for(i=1;i+1;i++){
//
//        }
//    }
}
